package com.bristua.barcode.job;

import com.bristua.barcode.common.constants.Constants;
import com.bristua.barcode.common.util.JsonUtil;
import com.bristua.barcode.job.bo.StandardOrder;
import com.bristua.barcode.order.model.bo.JialianOrder;
import com.bristua.barcode.supplier.biz.GetChannelRequestConfigBiz;
import com.bristua.barcode.supplier.dao.TQrCodeCookieMapper;
import com.bristua.barcode.supplier.dao.TSupplierMapper;
import com.bristua.barcode.supplier.model.TChannelRequestConfig;
import com.bristua.barcode.supplier.model.TQrCode;
import com.bristua.barcode.supplier.model.TQrCodeCookie;
import com.bristua.barcode.supplier.model.TSupplier;
import com.bristua.barcode.supplier.model.condition.TQrCodeCookieExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2019/9/10.
 */
@Service
public class GetJiaLianOrderImpl implements IGetOrder {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private TQrCodeCookieMapper tQrCodeCookieMapper;

    @Resource
    private TSupplierMapper tSupplierMapper;

    @Autowired
    private GetChannelRequestConfigBiz getChannelRequestConfigBiz;

    @Override
    public List<StandardOrder> getOrder(String orderAmt, String tranStartDate, String systemNo, TQrCode tQrCode) {
        String supplierId = tQrCode.getSupplierId();
        TQrCodeCookieExample tQrCodeCookieExample = new TQrCodeCookieExample();
        tQrCodeCookieExample.createCriteria().andSupplierIdEqualTo(supplierId);
        List<TQrCodeCookie> tQrCodeCookieWithBLOBsList = tQrCodeCookieMapper.selectByExampleWithBLOBs(tQrCodeCookieExample);
        if (tQrCodeCookieWithBLOBsList != null && tQrCodeCookieWithBLOBsList.size() > 0) {
            TQrCodeCookie tQrCodeCookieWithBLOBs = tQrCodeCookieWithBLOBsList.get(0);
            TChannelRequestConfig channelRequestConfig = getChannelRequestConfigBiz.getChannelRequestConfig(tQrCodeCookieWithBLOBs.getChannelId());
            String url = channelRequestConfig.getUrl();
            StringBuilder newParams = new StringBuilder();
            newParams.append("&tradeTimeStart=").append(URLEncoder.encode(tranStartDate)).append("&tradeTimeEnd=")
                    .append(URLEncoder.encode(getEndTime(tranStartDate)));
            String result = HttpClientUtils.httpRequest(url, newParams.toString(),tQrCodeCookieWithBLOBs.getContent(), channelRequestConfig);
            Map map = JsonUtil.json2Map(result);

            if (map.get("data") != null && map.get("data") instanceof List) {
                List<JialianOrder> jialianOrderList = (List<JialianOrder>) map.get("data");
                if(jialianOrderList.size()>0){
                    List<StandardOrder> standardOrderList = new ArrayList<>();
                    for(JialianOrder jialianOrder:jialianOrderList){
                        StandardOrder standardOrder = new StandardOrder();
                        switch (jialianOrder.getStatus()) {
                            case "1":
                                standardOrder.setPayStatus(Constants.WAIT_PAY);
                                break;
                            case "2":
                                standardOrder.setPayStatus(Constants.PAY_SUCCESS);
                                break;
                            default:
                                standardOrder.setPayStatus(Constants.PAY_FAIL);
                                break;
                        }
                        standardOrder.setPayTime(jialianOrder.getTradeTime());
                        standardOrder.setPayType(jialianOrder.getAcceptanceType().contains("微信") ? "1" : "2");
                        standardOrder.setSystemNo(jialianOrder.getOrderNo());
                        standardOrder.setPayAmt(Long.valueOf(jialianOrder.getFinnalAmount()));
                        standardOrderList.add(standardOrder);
                    }
                    return standardOrderList;
                }
            }else{//连接不上，这时需要通知
                TSupplier tSupplier = tSupplierMapper.selectByPrimaryKey(tQrCode.getSupplierId());
                logger.error("供应商:"+tSupplier.getSupplierName()+",登录失败，请重新登录");
            }
        }
        return null;
    }

    private String getEndTime(String startTime) {
        try {
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = time.parse(startTime);
            Date afterDate = new Date(d.getTime() + 200000);//后3分钟
            return time.format(afterDate);
        } catch (Exception ex) {
            logger.error("时间解析异常", ex);
        }
        return null;
    }
}
